package fun.shuofeng.juc.reentranlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo03 {
    public static final ReentrantLock LOCK = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                // 尝试等待2s获取锁
                if (!LOCK.tryLock(2, TimeUnit.SECONDS)) {
                    System.out.println(Thread.currentThread().getName() + " 获取锁失败");
                    return;
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " 获取锁失败");
                return;
            }
            try {
                System.out.println(Thread.currentThread().getName() + "获取锁成功");
            } finally {
                LOCK.unlock();
            }
        }, "t1");

        // 主线程加锁
        LOCK.lock();
        System.out.println(Thread.currentThread().getName() + " 得到锁");
        t1.start();
        // 1s后释放锁
        TimeUnit.SECONDS.sleep(1);
        System.out.println(Thread.currentThread().getName() + " 释放锁");
        LOCK.unlock();
    }
}
